<template>
  <div>
    <el-dialog
      title="新增目录"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属学科" prop="subjectID">
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName">
          <el-input v-model="form.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {simpleSubject} from '@/api/subjects'
import {tagsAdd, tagsDetail, tagsUpdate} from '@/api/tags'
export default {
  name: 'AddTags',
  props: {
    dialogVisible: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        subjectID: '',
        tagName: ''
      },
      options: [],
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' },
        ],
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
        ]
      }
    }
  },
  mounted() {
    this.getSubList()
  },
  methods: {
    closeDialog() {
      this.$emit('close-dialog')
      // 清空表单
      this.form = {
        subjectID: '',
        tagName: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields();
    },
    async getSubList() {
      const res = await simpleSubject() 
      // console.log(res);
      this.options = res
    },
    confirm() {
      // 兜底校验
      this.$refs.form.validate(async (valid) => {
          if (valid) {
            // 校验通过
            // 判断新增还是编辑
            if(!this.form.id) {
              // 调新增接口
              await tagsAdd(this.form)
            }else {
              // 编辑接口
              await tagsUpdate(this.form)
            }
            // 提示用户
            this.$message.success(`${this.form.id ? "更新成功" :"新增成功"}`)
            // 关闭弹窗
            this.closeDialog()
            // 刷新列表
            this.$emit('update-list')
          } 
        });
    },
    // 数据回显
    async getDeatil(id) {
      const res = await tagsDetail(id)
      this.form = res
    }
  }
}
</script>

<style>

</style>